package com.psp.stockinterface.service.impl;

import java.util.List;
import java.util.Map;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.psp.stockinterface.mapper.StockInterfaceMapper;
import com.psp.stockinterface.domain.StockInterface;
import com.psp.stockinterface.service.IStockInterfaceService;

import javax.annotation.Resource;

/**
 * 接口Service业务层处理
 *
 * @author tiger
 */
@Service
public class StockInterfaceServiceImpl implements IStockInterfaceService {
    @Resource
    private StockInterfaceMapper stockInterfaceMapper;

    /**
     * 查询接口
     *
     * @param id 接口主键
     * @return 接口
     */
    @Override
    public StockInterface selectStockInterfaceById(String id) {
        return stockInterfaceMapper.selectStockInterfaceById(id);
    }

    /**
     * 查询接口列表
     *
     * @param stockInterface 接口
     * @return 接口
     */
    @Override
    public List<StockInterface> selectStockInterfaceList(StockInterface stockInterface) {
        return stockInterfaceMapper.selectStockInterfaceList(stockInterface);
    }

    /**
     * 新增接口
     *
     * @param stockInterface 接口
     * @return 结果
     */
    @Override
    public int insertStockInterface(StockInterface stockInterface) {
        stockInterface.setId(IdUtils.fastSimpleUUID());
        stockInterface.setCreateTime(DateUtils.getNowDate());
        return stockInterfaceMapper.insertStockInterface(stockInterface);
    }

    /**
     * 修改接口
     *
     * @param stockInterface 接口
     * @return 结果
     */
    @Override
    public int updateStockInterface(StockInterface stockInterface) {
        stockInterface.setUpdateTime(DateUtils.getNowDate());
        return stockInterfaceMapper.updateStockInterface(stockInterface);
    }

    /**
     * 批量删除接口
     *
     * @param ids 需要删除的接口主键
     * @return 结果
     */
    @Override
    public int deleteStockInterfaceByIds(String[] ids) {
        return stockInterfaceMapper.deleteStockInterfaceByIds(ids);
    }

    /**
     * 删除接口信息
     *
     * @param id 接口主键
     * @return 结果
     */
    @Override
    public int deleteStockInterfaceById(String id) {
        return stockInterfaceMapper.deleteStockInterfaceById(id);
    }

    /**
     * 批量新增接口
     *
     * @param stockInterfaceList 接口
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchInsertStockInterface(List<StockInterface> stockInterfaceList) {
        stockInterfaceList.forEach(n -> {
            n.setId(IdUtils.fastSimpleUUID());
            n.setCreateTime(DateUtils.getNowDate());
            n.setCreateBy(SecurityUtils.getUsername());
        });
        stockInterfaceMapper.batchInsertStockInterface(stockInterfaceList);
    }

    /**
     * 批量更新接口
     *
     * @param stockInterfaceList 接口
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchUpdateStockInterface(List<StockInterface> stockInterfaceList) {
        stockInterfaceList.forEach(n -> {
            n.setUpdateTime(DateUtils.getNowDate());
            n.setUpdateBy(SecurityUtils.getUsername());
        });
        stockInterfaceMapper.batchUpdateStockInterface(stockInterfaceList);
    }

    /**
     * 测试接口是否可用
     *
     * @param stockInterface 接口信息
     * @return 接口返回结果
     */
    @Override
    public String testInterface(StockInterface stockInterface) {
        stockInterface.setAccessTime(DateUtils.getNowDate());
        List<Map<String, String>> header = null;
        if (StringUtils.isNotEmpty(stockInterface.getHeader())) {
            header = JSON.parseObject(stockInterface.getHeader(), new TypeReference<List<Map<String, String>>>() {
            });
        }
        String result;
        try {
            String url = stockInterface.getUrl() + stockInterface.getParameter().trim();
            HttpRequest request = HttpRequest.get(url);
            if (header != null && header.size() > 0) {
                for (Map<String, String> map : header) {
                    request.header(map.get("name"), map.get("value"));
                }
            }
            result = request.execute().body();
            // 手动根据返回内容判断接口是否调用成功
            stockInterface.setStatus(checkIfOkByApiResult(result) ? 0 : 1);
            stockInterface.setResponseContent(result.length() > 15000 ? result.substring(0, 15000) : result);
            this.updateStockInterface(stockInterface);
        } catch (Exception e) {
            e.printStackTrace();
            stockInterface.setStatus(1);
            stockInterface.setResponseContent(e.toString());
            this.updateStockInterface(stockInterface);
            result = null;
        }
        return result;
    }

    /**
     * 手动根据返回内容判断接口是否调用成功
     *
     * @param result 接口返回结果
     * @return 结果是否是正确内容，true对false错
     */
    boolean checkIfOkByApiResult(String result) {
        boolean b = true;
        if (result == null || result.equals("")) {
            return false;
        }
        if (result.length() < 10) {
            return false;
        }
        if (result.contains("服务器错误") || result.contains("找不到文件或目录")) {
            return false;
        }
        return b;
    }
}
